package edu.imac.angryfood.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class IOJDom {

	static Document document;
	static Element racine;
	/****************** Design pattern singleton ******************/
	private IOJDom () { }
	private static IOJDom io = new IOJDom();
	public static IOJDom getInstance () { return io; }
	/****************** Fin design pattern ******************/

	private static String fileName = "res/players/Comptes.xml";

	/**
	 * load a file
	 */

	/**
	 * load the comptes.xml file
	 */

	public static void loadFile (  ) {
		SAXBuilder sxb = new SAXBuilder();

		try {
			document=sxb.build(new File(fileName));
			racine = document.getRootElement();

		}
		catch (Exception e) {
			System.out.print("\nImpossible de lire le fichier xml \n");
			System.out.print(e.toString());

		}
	}


	/**
	 * Add a new account
	 * @param c Account to be added
	 */
	public static void addAcount(Account c){
		Element cpt = new Element("compte");
		Element n = new Element("nom");

		Element pa = new Element("password");
		Element l = new Element("last_level");
		Element s = new Element("max_score");

		String nom = c.getName();

		String pass = c.getPassword();
		String level = c.getLast_level();
		String score = Integer.toString(c.getMax_score());

		racine.addContent(cpt);
		cpt.addContent(n);

		cpt.addContent(pa);
		cpt.addContent(l);
		cpt.addContent(s);
		n.setText(nom);

		pa.setText(pass);
		l.setText(level);
		s.setText(score);

		record(fileName);
	}


	static void record(String file)
	{
		try
		{
			XMLOutputter outputFile = new XMLOutputter(Format.getPrettyFormat());
			outputFile.output(document, new FileOutputStream(file));
		}
		catch (java.io.IOException e){}
	}

	/**
	 * load the accounts
	 * @return arraylist of the accounts
	 */
	public static ArrayList<Account> loadAccount(){

		ArrayList<Account> cpts = new ArrayList<Account>();
		ArrayList<Integer> score_by_level = new ArrayList<Integer>();

		List<?> listComptes = racine.getChildren("compte");
		String name;
		String pass;
		int score;
		String lastlevel;
		Iterator<?> i = listComptes.iterator();
		
		while(i.hasNext())
		{
			Element courant = (Element)i.next();

			name =courant.getChild("nom").getText();

			pass =courant.getChild("password").getText();
			lastlevel=courant.getChild("last_level").getText();
			score = Integer.parseInt(courant.getChild("max_score").getText());

			Iterator<?> j = courant.getChildren("level").iterator();
			Element ec = courant.getChild("level");
			while(j.hasNext()) 
				{
				ec= (Element)j.next();
				
				score_by_level.add(Integer.parseInt(ec.getText()));
				
			}

			cpts.add(new Account(name,pass,lastlevel,score,score_by_level));
			score_by_level=null; 
			score_by_level=new ArrayList<Integer>();
		}

		return cpts;
	}


	/**
	 * modify the score of the level
	 * @param name name of the player
	 * @param score score of the player
	 * @param string
	 */
	public static void modifScoreLevel(String name, int score,String string)
	{
		String lastlevel;
		int oldScore;
		String element_score = "max_score";
		String element_level ="last_level";

		List<?> listEtudiant = racine.getChildren("compte");
		Iterator<?> i = listEtudiant.iterator();

		while(i.hasNext())
		{
			Element courant = (Element)i.next();
			if(courant.getChild("nom").getText().equals(name)){

				lastlevel = courant.getChild("last_level").getText();
				
				oldScore = Integer.parseInt(courant.getChild("max_score").getText());

				
				if((lastlevel.charAt(0)<string.charAt(0))){
					courant.removeChild(element_level);
					Element l = new Element(element_level);
					l.setText(string);
					courant.addContent(l);
				}
				if(((string.charAt(0)==lastlevel.charAt(0)))){
					if((lastlevel.charAt(2)) <= string.charAt(2)){
						courant.removeChild(element_level);
						Element l = new Element(element_level);
						l.setText(string);
						courant.addContent(l);
					}
				}
				if(oldScore < score){
					courant.removeChild(element_score);
					Element s = new Element(element_score);
					s.setText(Integer.toString(score));
					
					courant.addContent(s);
				}

			}

		}
		record(fileName);
	}	
	/**
	 * Change the best score of the level
	 * @param name of the xml
	 * @param new score to be added
	 * @param name of the level
	 */
	public static void changeScoreByLevel(String nom, int score,String level){
		String element_level = "level";
	    String lastlevel;
		List<?> listEtudiant = racine.getChildren("compte");
		Iterator<?> i = listEtudiant.iterator();
		//On parcours la liste grce  un iterator
		while(i.hasNext())
		{
			Element courant = (Element)i.next();
			if(courant.getChild("nom").getText().equals(nom)){ // si le noeud courant est celui du joueur nom
				lastlevel=courant.getChild("last_level").getText();

				if((level.charAt(0)<=lastlevel.charAt(0)) || ((level.charAt(0)==lastlevel.charAt(0)) && (level.charAt(2) <= lastlevel.charAt(2)) ) ){// si le niveau a modifier a dj t atteint, le recuprer et analyser le score
					
					Iterator<?> j = courant.getChildren("level").iterator();// sert a parcourir tout les noeud <level>
					Element ec = courant.getChild("level");
					while(j.hasNext())
						{
						ec= (Element)j.next();
						
						if(ec.getAttributeValue("id").equals(level)){//rcupre le noeud level ayant pour attribut id =level	
							int valeur=Integer.parseInt(ec.getText());// valeur du noeud a tester
							if(valeur<score){
								ec.setText(Integer.toString(score));
							}
						}
					}
				}else{ //Le niveau n'avait pas t atteint. Il faut donc aussi modifier le noeud max_level
					//creer un element level
					Element l = new Element(element_level);
					l.setAttribute("id", level);			
					l.setText(Integer.toString(score));
					courant.addContent(l);
					courant.removeChild("last_level");
					Element s = new Element("last_level");
					s.setText(level);
					courant.addContent(s);
				}
			}
		}
		record(fileName);
	}


	/**
	 * Delete an account from the xml
	 * @param c name of the account to be removed
	 */

	public static void deleteAccount(String c){
		
		List<?> listEtudiant = racine.getChildren("compte");
		Iterator<?> i = listEtudiant.iterator();

		while(i.hasNext())
		{
			Element courant = (Element)i.next();
			if(courant.getChild("nom").getText().equals(c)){
				 courant.setName("player_deleted");
			}
		}
		racine.removeChildren("player_deleted");	
		
		record(fileName);	
		

	}

}
